﻿using Common.Builders.Interfaces;
using Common.Cryptography;
using Common.Entities;
using Infrastructure.Interfaces;

namespace Infrastructure.Services
{
    public class UserEncryptor : IUserEncryptor
    {
        private readonly IDataEncryptor _dataEncryptor;
        private readonly IUserBuilder _userBuilder;

        private const string EncryptionKey = "aksurhtn_ciqp329xc9i1lp";

        public UserEncryptor(IDataEncryptor dataEncryptor, IUserBuilder userBuilder)
        {
            _dataEncryptor = dataEncryptor;
            _userBuilder = userBuilder;
        }

        public User SecureUser(User user)
        {
            var securedPassword = _dataEncryptor.Encrypt(user.Password, EncryptionKey);
            var securedAccounts = new UserAccounts();

            if (user.UserAccounts != null)
            {
                foreach (var account in user.UserAccounts.Accounts)
                {
                    var accountPassword = _dataEncryptor.Encrypt(account.AccountPassword, EncryptionKey);
                    securedAccounts.Add(new UserAccount(account.AccountName, accountPassword, account.SocialNetwork));
                }
            }

            return _userBuilder.WithUserName(user.UserName).WithPassword(securedPassword)
                   .WithUserAccounts(securedAccounts).Build();
        }

        public User UnsecureUser(User user)
        {
            var password = _dataEncryptor.Decrypt(user.Password, EncryptionKey);
            var accounts = new UserAccounts();

            foreach (var account in user.UserAccounts.Accounts)
            {
                var accountPassword = _dataEncryptor.Decrypt(account.AccountPassword, EncryptionKey);
                accounts.Add(new UserAccount(account.AccountName, accountPassword, account.SocialNetwork));
            }

            return _userBuilder.WithUserName(user.UserName).WithPassword(password)
                   .WithUserAccounts(accounts).Build();
        }

        public UserAccount UnsecureUserAccount(UserAccount userAccount)
        {
            var decryptedAccountPassword = _dataEncryptor.Decrypt(userAccount.AccountPassword, EncryptionKey);
            return new UserAccount(userAccount.AccountName, decryptedAccountPassword, userAccount.SocialNetwork);
        }
    }
}
